﻿<%@ Page Title="Promotion Engine -  Promotion Customer Exclusive" Language="C#" MasterPageFile="~/PromotionPage.Master"
    AutoEventWireup="true" CodeBehind="PromotionCustomerExclude.aspx.cs" Inherits="PromotionEngine.PromotionCustomerExclude" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPromotionPage" runat="server">
    <script type="text/javascript">
        var oPromotionCustomerExclusive = {};
        var oReferenceValueEx;
        var isInsert = false;
        var sourceCustomerPropertyEx;
        var girdEx;
        var editRowIndexEx;
        function sourceTypeDropDownEditor(container, options) {
            $('<input required data-text-field="ReferenceName" data-value-field="ReferenceValue" ID="ReferenceValue" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            autoBind: false,
                            filter: "contains",
                            suggest: true,
                            optionLabel: "[Select Source Type]",
                            dataSource: oReferenceValueEx,
                            change: function (e) {
                                var cmb = this;
                                // selectedIndex of -1 indicates custom value
                                if (cmb.selectedIndex < 0 && !viewModel.allowCustomValues) {
                                    cmb.value(null); // or set to the first item in combobox
                                }
                                else {
                                    var items = $("#gridCustomerEx").data("kendoGrid").dataSource.data();
                                    var item = items[editRowIndexEx];
                                    item.set('SourceValueName', '')
                                    item.set('SourceValue', '')
                                }
                            }
                        });

        }
        function sourceValueDropDownEditor(container, options) {
            $('<input disabled placeholder="Select Source Value" style="width:95%;" name="SourceValueName" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;cursor: pointer;" onclick="OpenSourceValue()" title="Choose value" ></span>').appendTo(container);
            $('<span class="k-invalid-msg" data-for="SourceValueName"></span>').appendTo(container);
        }
        function OpenSourceValue() {
            var rowData = $('#gridCustomerEx').data().kendoGrid.dataSource.data()[editRowIndexEx];
            if (rowData != null) {
                $("#sourceValueList").empty();
                var url = "";
                var title = "";
                //Customer
                if (rowData.SourceType == "1") {
                    url = "CustomerList.aspx";
                    title = "List of Customers";
                }
                //Property
                else if (rowData.SourceType == "2") {
                    url = "PropertySelectedList.aspx?PropertyType=customer";
                    title = "List of Customer Property";
                }
                //Query string
                else if (rowData.SourceType == "3") {
                    url = "BuildingQuery.aspx?Query=" + rowData.SourceValueName;
                    title = "Building Query String";
                }
                if (url.length > 0) {
                    var wnd = $("#sourceValueList")
                        .kendoWindow({
                            title: title,
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1000,
                            height: 550,
                            content: { type: "POST", url: url, data: {} },
                            iframe: true
                        }).data("kendoWindow");
                    wnd.setOptions({
                        title: title
                    });
                    wnd.center().open();
                }
            }
        }
        function ChooseCustomer(customerID, customerName) {
            var rowData = $('#gridCustomerEx').data().kendoGrid.dataSource.data()[editRowIndexEx];
            rowData.set('SourceValueName', customerName)
            rowData.set('SourceValue', customerID);
            $("#sourceValueList").data("kendoWindow").close();
        }
        function ChooseProperty(propertyDetailID, propertyDetailName) {
            var rowData = $('#gridCustomerEx').data().kendoGrid.dataSource.data()[editRowIndexEx];
            rowData.set('SourceValueName', propertyDetailName)
            rowData.set('SourceValue', propertyDetailID);
            $("#sourceValueList").data("kendoWindow").close();
        }
        function ChooseQuery(Query) {
            var rowData = $('#gridCustomerEx').data().kendoGrid.dataSource.data()[editRowIndexEx];
            rowData.set('SourceValueName', Query)
            $("#sourceValueList").data("kendoWindow").close();
        }
        //Get reference
        function GetReference() {
            $.ajax({
                type: "GET",
                url: "PromotionCustomerExclude.aspx/GetAllReferenceValueSourceType",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oReferenceValueEx = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        //Get Customer Property
        function GetCustomerPropertys() {
            $.ajax({
                type: "GET",
                url: "PromotionCustomerInclude.aspx/GetCustomerPropertys",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    sourceCustomerPropertyEx = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        $(document).ready(function () {
            
            GetReference();
            //GetCustomerPropertys();
            var promotionID = $('#<%=lblPromotionIDEx.ClientID%>').val();
            var promotionCode = $('#<%=lblPromotionCodeEx.ClientID%>').text();
            var promotionName = $('#<%=lblPromotionNameEx.ClientID%>').text();
            $("#MasterPromotionCode").val(promotionCode);
            $("#MasterPromotionName").val(promotionName);
            $("#MasterPromotionID").val(promotionID);
            if (promotionID != null) {
                girdEx = $("#gridCustomerEx").kendoGrid({
                    dataSource: {
                        transport: {
                            read: {
                                type: "GET",
                                url: "PromotionCustomerExclude.aspx/GetCustomerExclude",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json"
                            },
                            destroy: {
                                type: "GET",
                                url: "PromotionCustomerExclude.aspx/DeleteCustomerExclude",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json"
                            },
                            parameterMap: function (data, operation) {
                                if (operation === "read") {
                                    return { promotionID: promotionID };
                                }
                                if (operation === "destroy") {
                                    return { lineID: data.LineID };
                                }
                            },
                            error: function (a) {
                            },
                            serverPaging: true,
                            serverSorting: true,
                            serverFiltering: true
                        },
                        type: "odata", //Important!!!!
                        schema: {
                            data: function (a) {
                                if (a.d != null) {
                                    var data = a.d.Data;
                                    return data;
                                }
                            },
                            total: "d.Count",
                            model: {
                                id: "LineID",
                                fields: {
                                    LineID: { type: "number" },
                                    PromotionID: { type: "string" },
                                    ReferenceName: { type: "string" },
                                    SourceType: { type: "string" },
                                    SourceValue: { type: "string" },
                                    SourceValueName: { type: "string" }
                                }
                            }
                        }
                    },
                    //sortable: true,
                    pageable: {
                        pageSize: 20,
                        refresh: true
                    },
                    filterable: true,
                    reorderable: true,
                    resizable: true,
                    height: 370,
                    selectable: "row",
                    toolbar: [{ name: 'create', text: 'Add New' }, { name: 'excel'}],
                    excel: {
                        fileName: "Customer Exclude List.xlsx",
                        filterable: true
                    },
                    dataBound: onDataBound,
                    batch: true,
                    columns: [
                            { field: "LineID", title: "Property ID", width: 300, hidden: true },
                            { field: "PromotionID", title: "Property ID", width: 300, hidden: true },
                            { field: "ReferenceName", title: "ReferenceName", width: 300, hidden: true },
                            { field: "SourceType", title: "Source Type", width: 300, editor: sourceTypeDropDownEditor, template: "#=ReferenceName#" },
                            { field: "SourceValue", title: "Source Value", width: 300, hidden: true },
                            { field: "SourceValueName", title: "Source Value", width: 500, editor: sourceValueDropDownEditor, template: "#=SourceValueName#" },
                            { command: ["edit", "destroy"], title: "Action", width: "200px" }
                            ],
                    editable: {
                        mode: "inline",
                        confirmation: "Are you sure you want to remove this data?"
                    },
                    edit: function (e) {
                        if (e.model.isNew()) {
                            isInsert = true;
                            $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                        }
                        else {
                            isInsert = false;
                        }
                    },
                    save: function (e) {
                        
                        var listTextBox = $("input:text");
                        for (var i = 0; i < listTextBox.length; i++) {
                            var name = listTextBox[i].name;
                            if (name.length > 0) {
                                oPromotionCustomerExclusive[name] = $("[name=" + name + "]").val();
                            }
                        }
                        oPromotionCustomerExclusive.PromotionID = promotionID;
                        oPromotionCustomerExclusive.SourceType = $('#ReferenceValue').data("kendoDropDownList").value();
                        if ($.trim(oPromotionCustomerExclusive.SourceValueName) == '') {
                            
                            setMasterMessage("Please select Source Value.", "error");
                            return;
                        }
                        //Update or Insert Company
                        $.ajax({
                            type: "POST",
                            url: "PromotionCustomerExclude.aspx/UpdateCustomerExclude",
                            data: JSON.stringify({
                                oPromotionCustomerExclusive: JSON.stringify(oPromotionCustomerExclusive),
                                isInsert: isInsert
                            }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                girdEx.dataSource.read();
                                isInsert = false;
                                setMasterMessage("Operation complete successful!", "success");
                            },
                            error: function (xhr, status, err) {
                                var err = eval("(" + xhr.responseText + ")");
                                alert(err.Message);
                            }
                        });
                        this.refresh();
                    }
                }).data("kendoGrid");
            }
        });
        function onDataBound(e) {
            var grid = $("#gridCustomerEx").data("kendoGrid");
            $(grid.tbody).on("click", "td", function (e) {
                var row = $(this).closest("tr");
                editRowIndexEx = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
            });
            $(grid.tbody).on("blur", "td", function (e) {
                var row = $(this).closest("tr");
                var rowIdx = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
                var colName = $('#gridCustomerEx').find('th').eq(colIdx).text();
                var columnField = $('#gridCustomerEx').find("th").eq(colIdx).attr("data-field");
                var rowData = $('#gridCustomerEx').data().kendoGrid.dataSource.data()[rowIdx];
                if (columnField == 'SourceType') {
                }
            });
        }
    </script>
    <h3>
        &nbsp;Customer <span class="k-icon k-i-arrowhead-e"></span>Exclusive
    </h3>
    <h2 style="display: none">
        Promotion:&nbsp;
        <asp:Label ID="lblPromotionCodeEx" runat="server"></asp:Label>
        -
        <asp:Label ID="lblPromotionNameEx" runat="server"></asp:Label>
        <asp:HiddenField ID="lblPromotionIDEx" runat="server"></asp:HiddenField>
    </h2>
    <div id="sourceValueList">
    </div>
    <div id="gridCustomerEx">
    </div>
</asp:Content>
